package top.likeqc.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.likeqc.common.lang.Result;
import top.likeqc.entity.Class;
import top.likeqc.entity.Student;
import top.likeqc.service.IClassService;
import top.likeqc.service.IGradeService;
import top.likeqc.service.IStudentService;

import java.util.List;

/**
 * <p>
 * 班级表 前端控制器
 * </p>
 *
 * @author likeqc
 * @since 2022-04-10
 */
@RestController
@RequestMapping("/class")
public class ClassController extends BaseController {
    @Autowired
    IClassService classService;

    @Autowired
    IGradeService gradeService;

    @Autowired
    IStudentService studentService;

    /**
     * 查询 班级表
     * @param keyStr
     * @return
     */
    @GetMapping("")
    public Result list(String keyStr, Long gradeId) {
        QueryWrapper<Class> queryWrapper = new QueryWrapper<Class>().like(StringUtils.isNoneBlank(keyStr), "name", keyStr);
        if (gradeId != null) {
            queryWrapper.eq("grade_id", gradeId);
        }
        Page<Class> page = classService.page(getPage(), queryWrapper);
        // 查询班级信息
        page.getRecords().forEach(aClass -> aClass.setGrade(gradeService.getById(aClass.getGradeId())));
        return Result.success(page);
    }

    /**
     * 新增、修改 班级表
     * @param aclass
     * @return
     */
    @PostMapping("")
    public Result edit(@RequestBody Class aclass) {
        boolean b = classService.saveOrUpdate(aclass);
        // TODO 更新操作删除缓存

        if (b) {
            return Result.success(aclass);
        } else {
            return Result.fail("新增、修改年级，操作失败");
        }
    }

    /**
     * 删除 班级表
     * @param gradeIds
     * @return
     */
    @DeleteMapping("")
    public Result delete(@RequestBody List<Integer> gradeIds) {
        Student student = studentService.getOne(new QueryWrapper<Student>().in("grade_id", gradeIds));
        if (student != null) {
            return Result.fail("该班级还有学生，不嫩删除");
        }
        boolean b = classService.removeByIds(gradeIds);
        if (b) {
            return Result.success();
        } else {
            return Result.fail("删除年级，操作失败");

        }
    }

}
